package com.xtayfjpk.security.jsse;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import org.junit.Test;

public class HttpsUrlConnectionTest {
	
	@Test
	public void test() throws Exception {
		URL url = new URL("https://localhost:8443/");
		HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection());
		
		
		SSLContext context = SSLContext.getInstance("SSL");
		String keyStorePassword = "gitblit";
		KeyStore clientKeys = SimpleSSLServer.getKeyStore("D:\\java-app\\apache-tomcat-6.0.35\\conf\\clientKeyStore.p12", "pkcs12", keyStorePassword);
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		String privateKeyPassword = "gitblit";
		keyManagerFactory.init(clientKeys, privateKeyPassword.toCharArray());
		
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		String trustStorePassword = "gitblit";
		KeyStore serverTrustKeys = getKeyStore("D:\\java-app\\apache-tomcat-6.0.35\\conf\\clientTrustStore.jks", "jks", trustStorePassword);
		trustManagerFactory.init(serverTrustKeys);
		context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
		
		//使用SSL上下文创建SSLSocket
		SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();
		//如果服务端没设置需要认证客户端的话，可以不用设置SSLSocketFactory
		connection.setSSLSocketFactory(factory);
		
		connection.setDoInput(true);
		connection.setDoOutput(true);
		InputStream in = connection.getInputStream();
		String line = null;
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		while((line=reader.readLine())!=null) {
			System.out.println(line);
		}
	}
	
	public static KeyStore getKeyStore(String keyStorePath, String type, String keyStorePassword) throws Exception {
		KeyStore keyStore = KeyStore.getInstance(type);
		FileInputStream in = new FileInputStream(keyStorePath);
		keyStore.load(in, keyStorePassword.toCharArray());
		in.close();
		return keyStore;
	}
}
